package com.guilang.localmusic;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationView;
import com.youth.banner.Banner;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private final int requestCode = 1000;
    private DrawerLayout mDrawerLayout;
    private FrameLayout frameLayout_mine, frameLayout_cloud, frameLayout_find;
    private List<FrameLayout> frame_list = new ArrayList<>();
    private Button myfavor, mymusic, mydown, sign_in, mine, find, cloud, finishAll;
    private Banner banner;       //首页banner


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActivityCollector.addActivity(this);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //部署侧滑界面
        mDrawerLayout = findViewById(R.id.drawer_layout);
        NavigationView navView = findViewById(R.id.nav_view);
        //部署底部选择
        BottomNavigationView bottomNavigationView = findViewById(R.id.BottomBar);


        ActionBar actionBar = getSupportActionBar();
        //去除标题栏得文字
        actionBar.setDisplayShowTitleEnabled(false);
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
        }
        RequestPermission();        //申请权限
        InitButton_FrameLayout(); //绑定控件设置监听
        frameLayout_mine.setVisibility(View.VISIBLE); //设置首页面
        //获取配置文件信息
        readUserLogin();

        //适配Banner adapter
        banner.setBackgroundResource(R.drawable.banner);
        //frameLayout.setBackgroundResource(R.drawable.background);
        //frameLayout.getBackground().setAlpha(100);


        //底部导航栏设置点击
        bottomNavigationView.setSelectedItemId(bottomNavigationView.getMenu().getItem(2).getItemId());
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.minePage:
                        HideOtherFrameLayout(frameLayout_mine);
                        break;
                    case R.id.cloudPage:
                        HideOtherFrameLayout(frameLayout_cloud);
                        break;
                    case R.id.findPage:
                        HideOtherFrameLayout(frameLayout_find);
                        break;
                    default:
                        break;
                }
                return true;
            }
        });

        //侧滑事件点击
        navView.setCheckedItem(R.id.action_setting);
        navView.setCheckedItem(R.id.action_connect);
        navView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.action_setting:
                    case R.id.action_connect:
                        mDrawerLayout.closeDrawers();
                        break;
                    default:
                        break;
                }
                return true;
            }
        });

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.mymusic:
                Intent intent = new Intent(MainActivity.this, MySongs.class);
                startActivity(intent);
                break;
            case R.id.finishAll:
                ActivityCollector.finishAll();
            case R.id.sign_in:
                Intent intent_sign = new Intent(MainActivity.this, ActivitySign.class);
                startActivity(intent_sign);
                break;
            case R.id.mydown:
            case R.id.myfavor:
            default:
                break;
        }
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                mDrawerLayout.openDrawer(GravityCompat.START);
                break;
            default:
                break;
        }
        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.nav_menu_view, menu);
        return true;
    }


    //权限拒绝回调
    @Override
    public void onRequestPermissionsResult(int RequestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(RequestCode, permissions, grantResults);
        if (RequestCode == requestCode) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast toast = Toast.makeText(MainActivity.this, "Welcome !", Toast.LENGTH_SHORT);
            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("权限申请")
                        .setMessage("权限不足，确认后退出")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                finish();
                            }
                        })
                        .create()
                        .show();
            }
        }
    }

    private void RequestPermission() {
        //权限申请
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int permission = ContextCompat.checkSelfPermission(MainActivity.this,
                    Manifest.permission.READ_EXTERNAL_STORAGE);
            if (permission == PackageManager.PERMISSION_GRANTED) {
                //表示有权限
            } else {
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, requestCode);
            }
        }
    }

    private void InitButton_FrameLayout() {
        //主页按钮
        banner = findViewById(R.id.banner);
        mymusic = findViewById(R.id.mymusic);
        myfavor = findViewById(R.id.myfavor);
        mydown = findViewById(R.id.mydown);
        sign_in = findViewById(R.id.sign_in);
        finishAll = findViewById(R.id.finishAll);
        //设置点击
        //banner.setOnBannerListener((OnBannerListener) this);
        mymusic.setOnClickListener(MainActivity.this);
        myfavor.setOnClickListener(MainActivity.this);
        mydown.setOnClickListener(MainActivity.this);
        sign_in.setOnClickListener(MainActivity.this);
        finishAll.setOnClickListener(MainActivity.this);

        frameLayout_mine = findViewById(R.id.frame_mine);
        frameLayout_cloud = findViewById(R.id.frame_cloud);
        frameLayout_find = findViewById(R.id.frame_find);
        frame_list.add(frameLayout_mine);
        frame_list.add(frameLayout_cloud);
        frame_list.add(frameLayout_find);
    }

    private void HideOtherFrameLayout(FrameLayout frameLayout) {
        for (FrameLayout mframe : frame_list) {
            if (mframe != frameLayout) {
                mframe.setVisibility(View.GONE);
            } else {
                mframe.setVisibility(View.VISIBLE);
            }
        }
    }

    private void readUserLogin() {
        SharedPreferences preferences;
        preferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
        //获取本文中记住的用户名和密码
        UserLoginINFO.setIsRememberPwd(preferences.getBoolean("isRememberPwd", false));
        UserLoginINFO.setTel(preferences.getString("tel", null));
        UserLoginINFO.setUsr(preferences.getString("usr", null));
        UserLoginINFO.setPwd(preferences.getString("pwd", null));
        //判断是否已经登录
        UserLoginINFO.setIsLogin(preferences.getBoolean("isLogin",false));
        if(UserLoginINFO.getIsLogin()){
            //如果已经登录则获取账号的msg，lId，uId，头像，歌单ID，歌单列表ID
            UserLoginINFO.setlId(preferences.getString("lId", null));
            UserLoginINFO.setuId(preferences.getString("lId", null));
            UserLoginINFO.setMsg(preferences.getString("msg", null));
            UserLoginINFO.setAvatar(preferences.getString("avatar",null));
            UserLoginINFO.setGdId(preferences.getString("gdId",null));
            UserLoginINFO.setGdList(preferences.getString("gdList",null));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollector.finishAll();
    }
}